package online.lmds.sdmanage.common.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import online.lmds.sdmanage.main.message.entity.MqttLog;

import java.io.IOException;

/**
 * Json 相关工具类
 * Created by Sunny  An on 2017/2/22 0022.
 */
public class JsonUtils {

    private final static ObjectMapper objectMapper = new ObjectMapper();

    public static String objectToString(Object object) {
        try {
            return objectMapper.writeValueAsString(object);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static <T> T stringToObject(String string, Class<T> cls) {
        try {
            return objectMapper.readValue(string, cls);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }


    public static void main(String[] args) {
        String string = "{\n" +
                "    \"id\": 1,\n" +
                "    \"msgType\": 1,\n" +
                "    \"topic\": \"someTopic\",\n" +
                "    \"fromId\": 1,\n" +
                "    \"deviceId\": \"value\",\n" +
                "    \"deviceType\": \"Yeelight Color\",\n" +
                "    \"deviceTypeId\": 2,\n" +
                "    \"deviceStatus\": 2,\n" +
                "    \"mark\": \"mark12333\",\n" +
                "    \"data\": \"{\"status\\\": \\\"on\\\"}\",\n" +
                "    \"isReceive\": 1,\n" +
                "    \"cacheStatus\": 1\n" +
                "}";

        String string2 = "{\n" +
                "    \"msgType\": 1,\n" +
                "    \"topic\": \"someTopic\",\n" +
                "    \"fromId\": \"web-admin-01\",\n" +
                "    \"deviceType\": \"YEELIGHT_COLOR\",\n" +
                "    \"deviceId\": \"a7458298-1e23-3736-bbee-bce79e697319\",\n" +
                "    \"deviceStatus\":\"0\",\n" +
                "    \"mark\": \"some say..\",\n" +
                "    \"data\": {\n" +
                "        \"controlType\": \"SET_BRIGHT\",\n" +
                "        \"cmd\": \"cmd msg\",\n" +
                "        \"power\": 1,\n" +
                "        \"brighten\": 1,\n" +
                "        \"color\": 100,\n" +
                "        \"ctAbx\": 100\n" +
                "    }\n" +
                "}";

        MqttLog log = null;
        try{
            log = JsonUtils.stringToObject(string2, MqttLog.class);
        } catch (Exception e){
            System.out.println("无效的消息类型");
            return;
        }

        System.out.println(log.getData());
    }

}
